package com.authine.cloudpivot.ext.applicationservice;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.cola.dto.RequestContext;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.ext.domain.query.GoodsInputQuery;
import com.authine.cloudpivot.ext.domain.query.GoodsQuery;
import com.authine.cloudpivot.ext.domain.query.MallQuery;
import com.authine.cloudpivot.ext.domain.vo.CartVo;
import com.authine.cloudpivot.ext.domain.vo.GoodsPurchaseVO;
import com.authine.cloudpivot.ext.domain.vo.ShopVo;
import com.authine.cloudpivot.ext.domain.vo.VendorGoodsVO;
import com.authine.cloudpivot.ext.dto.*;
import com.authine.cloudpivot.ext.dto.system.OrganizationDto;
import com.authine.cloudpivot.ext.dto.system.UserDto;
import com.authine.cloudpivot.ext.enums.order.CartTypeEnum;
import com.authine.cloudpivot.ext.enums.system.OrganizationAttributeEnum;
import com.authine.cloudpivot.ext.service.ExternalInterfaceService;
import com.authine.cloudpivot.ext.service.impl.ExternalInterfaceServiceImpl;
import com.authine.cloudpivot.ext.utils.system.OrgAttributeUtils;
import com.authine.cloudpivot.ext.utils.system.OrgUtils;
import com.authine.cloudpivot.ext.utils.system.SessionUser;
import com.authine.cloudpivot.ext.utils.system.UserUtils;
import com.authine.common.util.ObjectMapperUtils;
import com.authine.hermes.app.launcher.service.ApplicationService;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

/**
 *
 */
@Path("ExternalInterface")
@Slf4j
public class ExternalInterface extends ApplicationService {

    ExternalInterfaceService extService = ExternalInterfaceServiceImpl.getInstance();


    @POST
    @Path("quotationIds")
    @Operation(summary = "根据报价商品ID查询企业采购商品", tags = CUSTOM_SERVICE)
    public GatewayResponse quotationIds(GatewayParam dto) {
        SessionUser sessionUser = new SessionUser();
        if (null == dto.getQuery()) {
            return GatewayResponse.failed("报价商品id 不能为空");
        }

        String quotationIds = String.valueOf(dto.getQuery().get("quotationIds"));

        List<String> quotationIdList = CollectionUtil.toList(quotationIds.split(","));

        if (quotationIdList.isEmpty()) {
            return GatewayResponse.failed("报价商品id 不能为空");
        }


        String userId = RequestContext.getCorpLoginId();

        OrganizationDto org = OrgUtils.getOrgByUserId();
        //获取组织id
        String orgId = org.getId();
        List<String> currentOrgIds = OrgUtils.getOrgListByOrgIds(Stream.of(orgId).collect(Collectors.toList()))
                .stream().map(OrganizationDto::getId).collect(Collectors.toList());
        List<String> customerOrgIds = null, vendorOrgIds = null, inquiryMemberId = null;

        //是供应商
        if (sessionUser.isVendor()) {
            vendorOrgIds = currentOrgIds;
        } else if (sessionUser.isCustomer()) {
            customerOrgIds = currentOrgIds;

            //是否开启年度采购权限
            boolean enabledAttribute = OrgAttributeUtils.isEnabledAttribute(orgId, OrganizationAttributeEnum.SELF_LOOP_PURCHASE);
            //若开启年度采购权限，则客户在多次采购目录只能看到自己的管理下的商品
            if (enabledAttribute) {

                inquiryMemberId = UserUtils.listSubMemberIds(userId);
            }
        }
        List<GoodsPurchaseVO> list = extService.queryPurchaseByQuotationIds(quotationIdList, customerOrgIds, vendorOrgIds, inquiryMemberId);

        return GatewayResponse.<List<GoodsPurchaseVO>>builder().data(list).count(list.size()).count(200).build();

    }

    @POST
    @Path("goodsPage")
    @Operation(summary = "根据客户商品料号和公司查询定标商品", tags = CUSTOM_SERVICE)
    public GatewayResponse goodsPage(GatewayParam2 dto) {

        GatewayResponse.GatewayResponseBuilder<Object> builder = GatewayResponse.builder();

        if (null == dto.getBody()) {
            return GatewayResponse.failed("参数不能为空");
        }

        List<Map<String, Object>> goodsList = dto.getBody();

        if (goodsList.isEmpty()) {
            return GatewayResponse.failed("参数不能为空");
        }

        Set<ShopVo> shopVo = extService.getShopVoByCompanyAndCustomerSku(new HashSet<>(goodsList));

        builder.data(shopVo).code(200).count(shopVo.size());

        return builder.build();
    }

    @POST
    @Path("goodsCart")
    @Operation(summary = "查看购物车" , tags = CUSTOM_SERVICE)
    public GatewayResponse goodsCart(GatewayParam dto) {

        GatewayResponse.GatewayResponseBuilder<Object> builder = GatewayResponse.builder();
        if (log.isDebugEnabled()) {
            log.debug("========================\n=========================查看购物车参数={}", dto);
        }
        if (null == dto.getQuery()) {
            return GatewayResponse.failed("参数不能为空");
        }
        Object cartTypeObj = dto.getQuery().get("cartType");

        Integer cartType = Integer.valueOf(cartTypeObj.toString());

        CartTypeEnum cte;
        if (1 == cartType) {
            cte = CartTypeEnum.DIRECT;
        } else if (2 == cartType) {
            cte = CartTypeEnum.INQUIRE;
        } else {
            return builder.code(-1).msg("请输入正确的类型！").build();
        }

        List<CartVo> cartList = extService.getCartList(cte);


        return builder.code(200).data(cartList).count(cartList.size()).build();
    }

    @POST
    @Path("shopGoodsPage")
    @Operation(summary = "根据条件查询采购目录" , tags = CUSTOM_SERVICE)
    public GatewayResponse shopGoodsPage(GatewayParam dto) {

        GatewayResponse.GatewayResponseBuilder<Object> builder = GatewayResponse.builder();

        Map<String, Object> query = dto.getQuery();
        String customerSku = (String) query.get("customerSku");
        String brand = (String) query.get("brand");
        String catalog = (String) query.get("catalog");
        String name = (String) query.get("name");
        String model = (String) query.get("model");
        String spec = (String) query.get("spec");
        Integer type = MapUtils.getInteger(query, "type");
        Integer page = MapUtils.getInteger(query, "page");
        Integer pageSize = MapUtils.getInteger(query, "pageSize");


        return extService.shopGoodsPage(customerSku, brand, catalog, name, model, spec, type, page, pageSize);
    }

    @POST
    @Path("vendorGoodsDelete")
    @Operation(summary = "批量删除供应商商品", tags = CUSTOM_SERVICE, description = "GoodsIds 和 clientGoodsIds的 值 是以','分割的字符串")
    public GatewayResponse vendorGoodsDelete(GatewayParam dto) {


        Map<String, Object> query = dto.getQuery();
        List<String> goodsIds = Arrays.stream(Optional.ofNullable((String) query.get("GoodsIds")).orElse("").split(","))
                .filter(Objects::nonNull).collect(Collectors.toList());
        List<String> clientGoodsIds = Arrays.stream(Optional.ofNullable((String) query.get("clientGoodsIds")).orElse("").split(","))
                .filter(Objects::nonNull).collect(Collectors.toList());

        return extService.vendorGoodsDelete(goodsIds, clientGoodsIds);
    }

    @POST
    @Path("goodsListUpdate")
    @Operation(summary = "批量修改供应商商品", tags = CUSTOM_SERVICE)
    public GatewayResponse goodsListUpdate(GatewayParam2 dto) {

        if (CollectionUtils.isEmpty(dto.getBody())) {
            return GatewayResponse.failed("参数为null!");
        }
        List<VendorGoodsVO> vendorGoodsVOS = ObjectMapperUtils.readValue(ObjectMapperUtils.toJSONString(dto.getBody()), VendorGoodsVO.class);
        return extService.toUpdateGoods(vendorGoodsVOS);
    }

    @POST
    @Path("goodsManagePaged")
    @Operation(summary = "分页查询供应商商品", tags = CUSTOM_SERVICE)
    public GatewayResponse goodsManagePaged(GatewayParam dto) {
        BasePageImpl page = JSONObject.parseObject(JSON.toJSONString(dto.getQuery()), BasePageImpl.class);
        GoodsQuery goodsQuery = JSONObject.parseObject(JSON.toJSONString(dto.getQuery()), GoodsQuery.class);

        try {
            return extService.pagedGoods(page.getRequestPage(), goodsQuery);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return GatewayResponse.failed(e.getMessage());
        }
    }


    @POST
    @Path("goodsSave")
    @Operation(summary = "保存供应商商品", tags = CUSTOM_SERVICE)
    public GatewayResponse goodsSave(GatewayParam2 dto) {

        List<VendorGoodsVO> goods = JSON.parseArray(JSON.toJSONString(dto.getBody()), VendorGoodsVO.class);

        if (goods.size() > 500) return GatewayResponse.failed("保存数量不能大于500条");

        UserDto currentUser = UserUtils.getCurrentUser();

        for (VendorGoodsVO good : goods) {
            GatewayResponse GatewayResponse = checkParam(good);
            if (GatewayResponse.getCode() == GatewayResponse.RESPONSE_ERR) {
                return GatewayResponse;
            }
            good.setClientId(currentUser.getClient_id());
        }

        List<GoodsInputQuery> list = GoodsInputQuery.toGoodsInputQueryList(goods, ConvertTypeEnum.APIV1);

        try {
            return extService.saveGoodsList(list);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return GatewayResponse.failed(e.getMessage());
        }

    }


    @POST
    @Path("goodsUpdate")
    @Operation(summary = "修改供应商商品", tags = CUSTOM_SERVICE)
    public GatewayResponse goodsUpdate(GatewayParam dto) {

        try {

            VendorGoodsVO vendorGoodsVO = JSONObject.parseObject(JSON.toJSONString(dto.getBody()), VendorGoodsVO.class);
            return extService.toUpdateGoods(Stream.of(vendorGoodsVO).collect(Collectors.toList()));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return GatewayResponse.failed("系统异常");
        }

    }


    public GatewayResponse checkParam(VendorGoodsVO param) {
        if (param == null) {
            return GatewayResponse.failed("参数不可为空！");
        } else {
            //品牌
            if (StringUtils.trimToNull(param.getBrand()) == null) {
                return GatewayResponse.failed("品牌不能为空！");
            }
            //名称
            if (StringUtils.trimToNull(param.getName()) == null) {
                return GatewayResponse.failed("名称不能为空！");
            }
            //型号
            if (StringUtils.trimToNull(param.getModel()) == null) {
                return GatewayResponse.failed("型号不能为空！");
            }
            //规格
            if (StringUtils.trimToNull(param.getSpec()) == null) {
                return GatewayResponse.failed("规格不能为空！");
            }
            //类目
            if (StringUtils.trimToNull(param.getCatalog()) == null) {
                return GatewayResponse.failed("类目不能为空！");
            }
            //单位
            if (StringUtils.trimToNull(param.getUnit()) == null) {
                return GatewayResponse.failed("单位不能为空！");
            }
            //税率
            if (param.getTaxRate() == null) {
                return GatewayResponse.failed("税率不能为空！");
            }
            //未税单价
            if (param.getPretaxPrice() == null && param.getPrice() == null) {
                return GatewayResponse.failed("未税单价和含税单价不能同时为空！");
            }
            //发货地
            if (StringUtils.trimToNull(param.getDeliveryPlace()) == null) {
                return GatewayResponse.failed("发货地不能为空！");
            }
        }
        return GatewayResponse.success();
    }


    @POST
    @Path("customerCreate")
    @Operation(summary = "客户创建订单", tags = CUSTOM_SERVICE)
    public GatewayResponse customerCreate(GatewayParam dto) {

        try {

            Object idsObj = dto.getQuery().get("ids");
            if (ObjectUtil.isEmpty(idsObj)) {
                return GatewayResponse.failed("参数不能为空");
            }
            List<String> ids;
            if (idsObj instanceof List) {
                ids = (List<String>) idsObj;
            } else {
                ids = Collections.singletonList(idsObj.toString());
            }
            return extService.createOrder(ids);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return GatewayResponse.failed("系统异常");
        }
    }

    @POST
    @Path("mallShop")
    @Operation(summary = "根据商品id查询商品详情", tags = CUSTOM_SERVICE)
    public GatewayResponse mallShop(GatewayParam dto) {


        try {
            String id = dto.getQuery().get("id").toString();
            return extService.pageMallGoodsByIds(id, true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return GatewayResponse.failed("系统异常");
        }
    }

    @POST
    @Path("mallShopPage")
    @Operation(summary = "分页查商城商品", tags = CUSTOM_SERVICE)
    public GatewayResponse mallShopPage(GatewayParam dto) {

        try {

            MallQuery query = JSONObject.parseObject(JSON.toJSONString(dto.getQuery()), MallQuery.class);
            return extService.pageMallGoods(query);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return GatewayResponse.failed("系统异常");
        }

    }

}
